﻿// copyright (c) 2025 author:fio66<fio66@foxmail.com>. All rights reserved.
// date: 2025-10-28 15:59:09

#include "src/common/utils.h"

#include <Windows.h>

#include <stdexcept>

namespace fio66::utils {
// 将wstring转换为string
std::string WStringToU8String(const std::wstring& wstr) {
  if (wstr.empty()) {
    return std::string();
  }

  int size_needed =
      WideCharToMultiByte(CP_UTF8, 0, wstr.data(), -1, NULL, 0, NULL, NULL);
  if (size_needed <= 0) {
    throw std::runtime_error("WideCharToMultiByte failed");
  }

  std::string str(size_needed - 1, 0);
  WideCharToMultiByte(CP_UTF8, 0, wstr.data(), -1, str.data(), size_needed,
                      NULL, NULL);

  return str;
}

// 将string转换为wstring
std::wstring U8StringToWString(const std::string& str) {
  if (str.empty()) {
    return std::wstring();
  }

  int size_needed = MultiByteToWideChar(CP_UTF8, 0, str.data(), -1, NULL, 0);
  if (size_needed <= 0) {
    throw std::runtime_error("MultiByteToWideChar failed");
  }

  std::wstring wstr(size_needed - 1, 0);
  MultiByteToWideChar(CP_UTF8, 0, str.data(), -1, wstr.data(), size_needed);

  return wstr;
}

// 将wstring转换为string
std::string WStringToString(const std::wstring& wstr) {
  if (wstr.empty()) {
    return std::string();
  }

  int size_needed =
      WideCharToMultiByte(CP_ACP, 0, wstr.data(), -1, NULL, 0, NULL, NULL);
  if (size_needed <= 0) {
    throw std::runtime_error("WideCharToMultiByte failed");
  }

  std::string str(size_needed - 1, 0);
  WideCharToMultiByte(CP_ACP, 0, wstr.data(), -1, str.data(), size_needed,
                      NULL, NULL);

  return str;
}

// 将string转换为wstring
std::wstring StringToWString(const std::string& str) {
  if (str.empty()) {
    return std::wstring();
  }

  int size_needed = MultiByteToWideChar(CP_ACP, 0, str.data(), -1, NULL, 0);
  if (size_needed <= 0) {
    throw std::runtime_error("MultiByteToWideChar failed");
  }

  std::wstring wstr(size_needed - 1, 0);
  MultiByteToWideChar(CP_ACP, 0, str.data(), -1, wstr.data(), size_needed);

  return wstr;
}
}  // namespace fio66::utils
